<template>
  <div class="change_price">
    <el-dialog title="新建变价单" class="noselect"
               v-dialogdrag=" { target:'.el-dialog__header',container:'.el-dialog',border:'.el-dialog__wrapper'}"
               :close-on-click-modal="false" :visible.sync="showDialog" :before-close="handleClose">
      <div style="margin: 20px;"></div>
      <el-form :model="modelForm" ref="modelForm" label-width="100px" class="price_form">
        <el-form-item label=" " prop="menuId" :rules="[{ required: true, message: '请选择下发商品库', trigger: 'change' }]">
          <div class="el-input el-input-group el-input-group--prepend">
            <el-tooltip style="border-right:0px solid #c0c0c0" placement="top" content="（选择下发商品库）">
              <div class="el-input-group__prepend">下发商品库</div>
            </el-tooltip>
            <el-select v-model="modelForm.menuId" filterable placeholder="请选择下发商品库" size="medium" class="w-100p" @change="getAllDishes();">
              <el-option
                v-for="item in menuList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="name" :rules="[]"
                      style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">商品</div>
            <el-input placeholder="请选择商品" auto-complete="off" :maxlength="5" size="medium">
              <el-button slot="append" icon="el-icon-caret-bottom" @click="goChose"></el-button>
            </el-input>
          </div>
          <div style="position: absolute;width:100%;background-color: #fff;z-index:99999999;">
            <div v-if="isDishes" style="border:1px solid #ccc;">
              <el-row :gutter="20" >
                <el-col :span="4" style="height:20vh;overflow-y: auto">
                  <div class="dishesItem" :class="{'activity':i.isSelect}" v-for="i in letterList" @click="goDishes(i)">
                    {{i.name}}
                  </div>
                </el-col>
                <el-col :span="20" class="text-left">
                  <div style="height:20vh;overflow-y: auto">
                  <div v-for="(j,index) in dishesList" >
                    <el-checkbox v-model="j.isSelect" style="width:100%;border-bottom:1px solid #f2f2f2"
                                 @change="getChange(index)">{{j.dishes_name}}<span v-if="j.spec_name">({{j.spec_name}})</span>
                    </el-checkbox>
                  </div>
                  </div>
                </el-col>
              </el-row>
              <div class="foot-bar-button" style="padding:10px;">
                <el-button type="primary" @click="goNext" size="medium">确定</el-button>
                <el-button @click="isDishes=false" size="medium">取消</el-button>
              </div>
            </div>

          </div>
          <div v-show="addInfo" style="width:100%">
            <el-table
              :header-cell-class-name="tableheaderClassName"
              :data="tableData"
             >
              <el-table-column
                prop="dishesName"
                label="已选商品"
              >
              <template slot-scope="scope">
               <span>{{scope.row.dishesName}}<span v-if="scope.row.spec_name">（scope.row.spec_name）</span></span>
              </template>
              </el-table-column>
              <el-table-column
                prop="oldPrice"
                label="原标准价"
              >
              </el-table-column>
              <el-table-column
                prop="price"
                label="变后标准价">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.price" @blur="moneyJiaoyan(scope.row,'price')" style="width:70%"
                            placeholder="0.00" size="medium" @focus="printNum"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="oldVipPrice"
                label="原会员价">
              </el-table-column>
              <el-table-column
                prop="vipPrice"
                label="变后会员价">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.vipPrice" @blur="moneyJiaoyan(scope.row,'vipPrice')" style="width:70%"
                            placeholder="0.00" size="medium" @focus="printNum"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="changeVipPrice"
                label="操作">
                <template slot-scope="scope">
              <el-button type="text" @click="goTableDel(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="reason" :rules="[{ required: true, message: '请输入变价原因', trigger: 'blur' }]">
          <el-input placeholder="请输入变价原因" v-model="modelForm.reason" auto-complete="off" :maxlength="35" size="medium">
            <template slot="prepend">
              <el-tooltip placement="top" content="请输入变价原因">
                <el-button tabIndex="-1">变价原因</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="effectiveTime" :rules="[{ required: true, message: '请输入生效日期', trigger: 'blur' }]">
          <div class="el-input el-input-group el-input-group--prepend">
            <div class="el-input-group__prepend">生效日期</div>
            <el-date-picker size="medium"
                            v-model="modelForm.effectiveTime"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            placeholder="选择生效日期"
                            style="width:100%;"
                            :picker-options="pickerOptions0"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="" :rules="[]"
                      style="position:relative">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">适用门店</div>
            <el-input placeholder="请选择" auto-complete="off" :maxlength="5" size="medium" v-model="disName">
              <el-button slot="append" icon="el-icon-caret-bottom" @click="isDistricts=!isDistricts"></el-button>
            </el-input>
          </div>
          <!--style="position: absolute;z-index:999999;background-color: #fff;width:100%;max-height: 30vh;overflow-y: auto;"-->
          <div v-if="isDistricts" class="branch_tree">
            <div style="text-align:left">
              <!-- style="overflow-y: auto;max-height:200px;"-->
              <el-tree
              id="myPanel" class="branch_tree_container"
              :data="treeData"
              show-checkbox
              node-key="value"
              ref="tree"
              :default-checked-keys="checkedKey"
              default-expand-all @check="getTreeValue"
              >
              </el-tree>
            </div>
            <!---->
          </div>
        </el-form-item>
      </el-form>
      <!--<div style="height: 180px;"></div>-->
      <div class="foot-bar-button">
        <el-button :disabled="canSave" type="primary" size="medium" @click="submitForm('modelForm')">
          <span v-if="canSave"><i class="el-icon-loading"></i>提交中</span>
          <span v-else>提交</span>
        </el-button>
        <!--<el-button type="primary" @click="submitForm('modelForm')" size="medium">提交</el-button>-->
        <el-button @click="resetForm('modelForm')" size="medium">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  //注意路径
  export default {
    props: ['isShow', 'id'],  //参数
    data() {
      return {
        canSave:false,
        isDishes: false,
        addInfo: false,
        isDistricts:false,
        modelForm: {},
        showDialog: false,
        activityId: "",
        isSave: true,
        downCategeryId: [],
        isUpdate: false,
        treeData: [],
        pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
          }
        },
        menuList: [],
        dishesList: [],
        allDishesList: [],
        letterList: [],
        tableData: [],
        disName:"",
        selectBransh:[],
        checkedKey:[]

      };
    },
    mounted(){
      let _this=this;
      document.addEventListener("click",function(event){
        var sp = document.getElementById("myPanel");
        if(sp){
          if(!sp.contains(event.target)){            //这句是说如果我们点击到了id为myPanel以外的区域
            _this.isDistricts=false;
          }
        }
      })
    },
    watch: {
      isShow: function (newValue, oldValue) {
        this.showDialog = newValue;
        this.canSave=false;
        this.disName='';
        if (newValue) {
          if (this.id != '') {
            this.activityId = this.id;
            this.isSave = false;
            this.isUpdate = true;
            this.$axios.get("dishes/changePrices/" + this.activityId + "/update").then(data => {
              this.modelForm = data.content.changePrice;
              this.menuList = data.content.menuList;
            });
          } else {
            this.isSave = true;
            this.isUpdate = false;
            this.tableData=[];
            this.$axios.get("dishes/changePrices/create").then(data => {
              data.content.changePrice.effectiveTime=this.moment().format("YYYY-MM-DD");
              this.modelForm = data.content.changePrice;
              this.menuList = data.content.menuList;
            });
          }
        }
      }
    },
    created() {
      window.this = this;


    },
    methods: {
      goTableDel(index){
        this.tableData.splice(index,1);
      },
      getTreeValue(){
        var branchs=this.$refs.tree.getCheckedNodes();
        console.log(branchs);
        this.selectBransh=[];
        this.checkedKey=[];
        this.disName="";
        for(var i=0;i<branchs.length;i++){
          if(branchs[i].iBranch){
            this.selectBransh.push(branchs[i].id);
            this.disName +=branchs[i].name+","
          }
        }

        if(this.selectBransh){
          for(var i=0;i<this.selectBransh.length;i++){
            this.checkedKey.push(this.selectBransh[i]+"_b")
          }
        }


      },
      tableheaderClassName(){
        return "table_header_cell_style";
      },
      printNum(){
        event.currentTarget.select();
      },
      goNext() {
        //点击确定，循环dishesList，得到选中的，push进tableData;
        var item=[];
        for(var i=0;i<this.dishesList.length;i++){
          if(this.dishesList[i].isSelect){
            item.push(this.dishesList[i]);
          }
        }
        console.log(item);
        if(item.length<=0){
          this.$message.error("请选择商品后点击确定");
          return;
        }
        var count=0;
        for(var i=0;i<item.length;i++){
          for(var j=0;j<this.tableData.length;j++){
                  console.log(item[i].spec_id,this.tableData[j].specId)
            if(item[i].dishes_id==this.tableData[j].dishesId && item[i].spec_id==this.tableData[j].specId){
              count++;
            }
          }
          if(count>0){
            this.$message.info("此商品已添加");
          }else{
            this.tableData.push({
              dishesName:item[i].dishes_name,
              dishesId:item[i].dishes_id,
              oldPrice:item[i].price,
              price:item[i].price,
              oldVipPrice:item[i].vip_price,
              vipPrice:item[i].vip_price,
              specName:item[i].spec_name,
              specId:item[i].spec_id
            })
          }
        }
        this.isDishes = false;
        this.addInfo = true;
      },
      getChange(index) {
        console.log(index);
        this.dishesList[index].dishes_name = this.dishesList[index].dishes_name
      },
      goDishes(item) {
        console.log(item);
        this.dishesList = [];
        for (var i = 0; i < this.allDishesList.length; i++) {
          if (item.name == this.allDishesList[i].letter) {
            this.dishesList = this.allDishesList[i].data;
            return;
          }
        }
        for(var i=0;i<this.letterList.length;i++){
          this.letterList[i].isSelect=false;
        }
        item.isSelect=true;
        item.name=item.name+'';
        console.log(item);
      },
      goChose() {
        if (this.modelForm.menuId == '' || this.modelForm.menuId == undefined) {
          this.$message.info("请先选择下发商品库");
          return;
        }
        this.isDishes = !this.isDishes;
        this.addInfo =false;

      },
      getAllDishes() {
        this.disName = '';
        this.checkedKey=[];
        this.$axios.get("dishes/dishesMenus/getDishesByMenu?menuId=" + this.modelForm.menuId).then(res => {
          if (res.success) {
            if (res.content.dishesList.length > 0) {
              this.dishesList=[];
              for(var i=0;i<res.content.dishesList.length;i++){
                res.content.dishesList[i].isSelect=false;
              }
              this.dishesList=res.content.dishesList;
              this.allDishesList = window.pySort(res.content.dishesList);
              console.log(this.dishesList);
              this.letterList = [];
              for (var i = 0; i < this.allDishesList.length; i++) {
                this.letterList.push({name: this.allDishesList[i].letter, isSelect: false});
              }
              if (this.letterList.length > 0) {
                this.letterList[0].isSelect = true;
              }
            }else{
              this.dishesList=[];
              this.allDishesList=[];
              this.letterList=[];
            }
            var tree = res.content.districts;
            this.newLabel(tree);
            this.treeData = tree;
            console.log(this.treeData);
          }
        }, res => {
        })
      },
      newLabel(newList) {
        if (newList) {
          for (var i = 0; i < newList.length; i++) {
            console.log(newList[i].iBranch);
            if(newList[i].iBranch){
              newList[i].value = newList[i].id + "_b";
            }else {
              newList[i].value = newList[i].id + "";
            }
            newList[i].label = newList[i].name;
            if (!newList[i].children || newList[i].children.length == 0) {
              newList[i].children = null;
            } else {
              for (var s = 0; s < newList[i].children.length; s++) {
                if(newList[i].iBranch){
                  newList[i].children[s].value = newList[i].children[s].id + "_b";
                }else {
                  newList[i].children[s].value = newList[i].children[s].id + "";
                }
                newList[i].children[s].label = newList[i].children[s].name;
                this.newLabel(newList[i].children[s].children);
              }
            }
          }
        }
        /*if (newList) {
          for (var i = 0; i < newList.length; i++) {
            newList[i].label = newList[i].name;
            newList[i].value = newList[i].id + "";
            if (!newList[i].children || newList[i].children.length == 0) {
              newList[i].children = null;
            } else {
              for (var s = 0; s < newList[i].children.length; s++) {
                newList[i].children[s].label = newList[i].children[s].name;
                newList[i].children[s].value = newList[i].children[s].id + "";
                this.newLabel(newList[i].children[s].children);
              }
            }
          }
        }*/
      },
      goBack() {
        this.router.go(-1);
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var data={};
            var selectBransh=[];

            if(this.selectBransh.length<=0){
              this.$message.error("请选择门店");
              return;
            }
            if(this.tableData.length<=0){
              this.$message.error("请选择商品");
              return;
            }
            data.branchs=this.selectBransh;
            data.changePrice=this.modelForm;
             data.dishes=this.tableData;
             if(this.canSave){
               return;
             }
             this.canSave=true;
            if (this.isSave) {
              this.$axios.post("dishes/changePrices/create",data,"json").then(data => {
                this.canSave=false;
                if (data.status == 200) {
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.$emit('addSuccess');
                } else {
                  this.$message.error(data.message);
                }

              })

            } else {
              this.modelForm._method = "PUT";
              this.$axios.put("dishes/changePrices/" + this.activityId + "/update",data,"json").then(data => {
                this.canSave=false;
                if (data.status == 200) {
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.$emit('addSuccess');
                } else {
                  this.$message.error(data.message);
                }
              })
            }
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$emit('close');
        this.tableData=[];
        this.showDialog = false;
      },
      handleClose(done) {
        this.$emit('close');
        done();
      },
      isNum(item, key) {
        var r = /^\+?[1-9][0-9]*$/;
        if (!r.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
      isDouble(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
      moneyJiaoyan(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
    }
  }
</script>
<style scoped>
  .dishesItem:hover {
    background-color: #f2f2f2;
    border-bottom: 1px solid #ccc;
    color:#409EFF !important;
  }

  .activity {
    color: #409EFF !important;
  }

  .tableheaderClassName {
    padding: 0px;
    height: 20px !important;
  }

</style>
